package leetcode.Y2024M5D23;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class S56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(x -> x[0]));
        int[][] res = new int[intervals.length][2];
        int index = 0;
        int indexR = 0;
        while (index < intervals.length) {
            int min = intervals[index][0];
            int max = intervals[index][1];
            // 条件需要优化
            while (index + 1 < intervals.length && max >= intervals[index + 1][0] && min <= intervals[index + 1][0]) {
                min = Math.min(min, intervals[index + 1][0]);
                max = Math.max(max, intervals[index + 1][1]);
                index++;
            }
            res[indexR] = new int[]{min, max};
            index++;
            indexR++;

        }
        int[][] r = new int[indexR][2];
        for (int i = 0; i < r.length; i++) {
            r[i][0] = res[i][0];
            r[i][1] = res[i][1];
        }
        return r;

    }

    @Test
    public void test() {
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        int[][] intervals1 = {{1, 4}, {4, 5}};
        int[][] intervals2 = {{1, 4}, {0, 0}};
        int[][] intervals3 = {{1, 4}, {0, 4}};
        System.out.println(Arrays.deepToString(merge(intervals3)));
        System.out.println(Arrays.deepToString(merge(intervals2)));
        System.out.println(Arrays.deepToString(merge(intervals)));
        System.out.println(Arrays.deepToString(merge(intervals1)));
    }

    @Test
    public void test1() {
        int[][] intervals = {{1, 4}, {0, 2}, {3, 5}};
        System.out.println(Arrays.deepToString(merge(intervals)));
    }

    @Test
    public void test2() {
        int[][] intervals = {{2, 3}, {4, 5}, {6, 7}, {8, 9}, {1, 10}};
        System.out.println(Arrays.deepToString(merge(intervals)));
    }
}
